import os
import mimetypes
from flask import jsonify,request

from video_core import VideoCore
from config import MOVIES_FOLDER
from base_oneword import get_random_oneword
from base_category import get_subdir_folders, get_subdir_videos, count_folder_walk,count_videos_in_tree
from mock_api import Mock_get_folders_videos,Mock_get_all_video_list
from security import is_safe_path  # 新增导入
from flask import Flask, render_template, request, redirect, url_for, send_from_directory, send_file, abort, make_response, jsonify
app = Flask(__name__)

app.config['HEADERS_USE_UTF8'] = True

@app.route('/')
def index():
    return '''
    <h1>我滴朋友，这个是后端的api接口网站</h1>
    <a href="http://http://10.60.165.110:5173">点我跳转</a>
    '''

@app.route('/api/oneword')
def return_oneword():
    """返回一条随机的一言"""
    return jsonify({"status": "success", "oneword": get_random_oneword()})

@app.route('/api/category')
def return_category():
    """返回总文件夹下面的所有子文件夹名称，用作分类"""
    """此处没有数据交互，不需要做安全检测"""
    return jsonify({"status": "success", "category": get_subdir_folders(MOVIES_FOLDER)})

@app.route('/api/get-folders-videos')
def get_folders_videos():
    """接受一个传参为folder，返回这个文件夹所有的子文件夹名字和这个文件夹内部的所有视频"""

    try:
        folder = request.args.get('folder', '')
        
        # 使用安全模块检测路径
        is_safe, full_path = is_safe_path(folder)
        if not is_safe:
            return jsonify({
                "status": "error",
                "message": full_path  # 这里会返回安全模块的提示信息
            }), 403
        
        # 调用中间层获取数据
        data = Mock_get_folders_videos(full_path)
        return jsonify({"status": "success", **data})
        
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/api/get-all-videos')
def get_all_videos():
    """接受一个传参为folder，返回这个文件夹所有的子文件夹和他们文件夹内的所有视频（遍历）"""

    try:
        folder = MOVIES_FOLDER
        
 
        # 调用中间层获取数据
        data = Mock_get_all_video_list(folder)
        return jsonify({"status": "success", **data})
        
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/api/videolist')
def get_video_list():
    """接受一个传参为folder，返回这个文件夹所有的子文件夹和他们文件夹内的所有视频（遍历）"""
    try:
        folder = request.args.get('folder', '')
        
        # 使用安全模块检测路径
        is_safe, full_path = is_safe_path(folder)
        if not is_safe:
            return jsonify({
                "status": "error", 
                "message": full_path
            }), 403
            
        # 调用中间层获取树状结构数据
        from mock_api import Mock_get_video_list
        tree_data = Mock_get_video_list(full_path)
        
        return jsonify({
            "status": "success", 
            "data": tree_data
        })
        
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

@app.route('/api/video')
def video_stream():
    """视频流API，通过查询参数接收视频路径并返回视频流"""
    try:
        # 从查询参数获取视频路径
        video_path = request.args.get('path', '')
        if not video_path:
            return jsonify({
                "status": "error", 
                "message": "缺少视频路径参数"
            }), 400
            
        # 使用安全模块检测路径
        is_safe, full_path = is_safe_path(video_path)
        if not is_safe:
            return jsonify({
                "status": "error", 
                "message": "路径错误",
            }), 403
            
        # 调用VideoCore处理视频流
        response = VideoCore.video(video_path)
        if isinstance(response, tuple):  # 处理错误响应
            return jsonify({"status": "error", "message": response[0]}), response[1]
        return response
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500


@app.after_request
def add_cors_headers(response):
    """添加跨域请求头"""
    origin = request.headers.get('Origin', '')
    allowed_origins = [
        # 'https://hacktb.com',
        'http://localhost',
        'http://127.0.0.1',
        'http://10.60.165.110'
    ]
    
    # 验证请求来源
    if any(origin.startswith(allowed) for allowed in allowed_origins):
        response.headers['Access-Control-Allow-Origin'] = origin
    
    response.headers['Access-Control-Allow-Methods'] = 'GET'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
    return response

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5001, debug=False)
